import requests
from bs4 import BeautifulSoup
import re

headers = {"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"}

def get_ymcart_goods_id(url):
    # url = "https://ds.dear-lover.com/products/parchment-cable-knit-drop-shoulder-loose-fit-sweater-dress-lc273764-p6016"

    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    # 查找包含ymcart_user_id的script标签
    script_content = soup.find('script', string=lambda text: text and 'ymcart_product_id' in text)  # 修改此处
    if script_content:
       # 使用正则表达式匹配ymcart_goods的值
        pattern = r'ymcart_goods\s*=\s*(\{.*?\});'
        match = re.search(pattern, script_content.text, re.DOTALL)
        if match:
        # 解析匹配到的字符串，移除不必要的空格和引号
            ymcart_goods_str = match.group(1).strip()
            if ymcart_goods_str:
                # 使用正则表达式匹配id属性
                id_pattern = r'"id":"(\d+)"'
                id_match = re.search(id_pattern, ymcart_goods_str)
                ymcart_goods_id = id_match.group(1)
                url2 = "https://ds.dear-lover.com/h-dropship-product.json?goods_id="+ymcart_goods_id
                print(url2)
                return url2
            else:
                print("无法找到ymcart_goods")
                return None
        else:
            print("无法找到ymcart_goods")
            return None


def get_goods_id(url):
    response = requests.get(url)
    if response.status_code == 200:
        response = response.json()
        zyi_list = []
        for item in response["data"]['variant_list']:
            zyi = {}
            size = item['base_name']
            size_str = re.sub(r'\([^)]*\)', '', size)
            inventory_sum = item['us_stock']+ item['cn_stock']
            zyi['size'] = size_str
            zyi['inventory_sum'] = inventory_sum
            print(zyi)
            zyi_list.append(zyi)

        print(zyi_list)
        return zyi_list

if __name__ == '__main__':
    # url = 'https://ds.dear-lover.com/products/black-star-graphic-crochet-knitted-summer-sweater-top-lc2724649-p2'
    # get_ymcart_goods_id(url)
    url = "https://ds.dear-lover.com/h-dropship-product.json?goods_id=2771042"

    get_goods_id(url)